import React from 'react';
import { connect } from 'dva';
import { Link, browserHistory } from 'dva/router';
import { Table, Row, Col, Form, Input, Icon, InputNumber, Radio, DatePicker, Select, Upload, Button, Switch, Modal, Popconfirm, Tabs, message } from 'antd';
const R = require('ramda');
import moment from 'moment'
const dateFormat = 'YYYY-MM-DD';
const { RangePicker } = DatePicker;
import RightContacts from '../../../utils/RightConstants';
import BizParams from '../../../components/commons/BizParams'
import CustomerDetail from '../../../components/customer/components/CustomerDetail';
import OrderDetail from '../../../components/order/components/OrderDetail';
import Statement from '../../../components/customer/statement/Statement';
import RightBox from "../../../components/commons/RightBox";
import Constants from "../../../utils/Constants";
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
export default connect(({ customerManage, drawer, orderManage, businessAgreement, statement, capital, customerReport, blacklist }) => ({ customerManage, drawer, orderManage, businessAgreement, statement, capital, customerReport, blacklist }))(
    Form.create()(class customerDetails extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
            }
        }

        componentDidMount() {
            this.props.dispatch({
                type: 'customerManage/queryCustomerManageList',
                payload: {
                    status: 4,
                    businessType: Constants.NUMBER_ONE
                }
            });
        }

        handleResetFields = () => {
            if (this.editCustomer) this.editCustomer.handleResetFields();
        }

        handleCancel = (flag) => {
            if (flag) {
                this.handleResetFields();
            }
        }

        onView = (record) => {
            this.handleOpenDetail(record, false, {}, "1", true);
        }

        onAddOrder = (record) => {

            if (R.isNil(record.waiter) || R.isNil(record.manager) || R.isNil(record.tgmanager)) {
                message.error("请确认跟单经理、业务经理、通关经理是否都已经全部分配完毕！");
                return;

            }

            if (!record.extId) { message.error("请完成客户交接单再下单"); return; }

            this.props.dispatch({
                type: 'customerManage/getCustomerById', payload: {
                    id: record.id, isApproval: false,
                    onSuccess: (customer) => {
                        this.props.dispatch({ type: 'orderManage/setCustomer', payload: { customer } });//查询联系人列表

                        if (customer.isblacklist) {
                            message.error("此客户在黑名单中,如需下单请移除黑名单!");
                            return;
                        }
                        if (!customer.hasDrawers) {
                            message.error("没有开票人或者开票人尚未审核通过，请先补充完整！");
                            return;
                        }
                        if (!customer.hasBuyers) {
                            message.error("请先添加境外贸易商！");
                            return;
                        }
                        this.props.dispatch({ type: 'orderManage/cleanOrder', payload: { cstid: record.id } });//清理order state 的已有订单信息
                        this.props.dispatch({ type: 'orderManage/queryDrawerList', payload: { cstId: record.id } });//查询开票人列表
                        //this.props.dispatch({ type: 'orderCost/queryOrderCost', payload: { id: record.id, status: "1"} });//查询费用列表
                        this.props.dispatch({ type: 'orderManage/queryLinkmanList', payload: { cstId: record.id } });//查询联系人列表
                        this.props.dispatch({ type: 'orderManage/queryAddressList', payload: { cstId: record.id } });//查询货物存放地址列表
                        this.props.dispatch({ type: 'orderManage/queryBuyerList', payload: { cstId: record.id } });//查询境外买家
                        this.props.dispatch({ type: 'orderManage/querySupplyGoods', payload: { cstId: record.id } });//查询境内货源地
                        this.refs.orderDetail.handleOpen(false, false, false, false, {}, "1");
                    }
                }
            });

        }


        onAddStatement = (record) => {
            if (record.csttype === '1') {
                message.info("当前是会员客户，不允许添加结算单！");
                return;
            }
            this.props.dispatch({ type: 'app/getRecAccListOfCstid', cstId: record.id });
            this.props.dispatch({ type: 'customerManage/getHistoryAmtList', payload: { cstId: record.id } });
            this.statement.handleOpen(false, {}, "1", record.id);
        }

        handleOpenDetail = (record, customerDisabled, searchConditions, tabActiveKey, editCustomerDisable) => {
            this.props.dispatch({
                type: 'customerManage/getCustomerById', payload: {
                    id: record.id, isApproval: false,
                    onSuccess: (customer) => {
                        let isblacklist = false;
                        if (customer.isblacklist) {
                            isblacklist = true;
                        }

                        this.props.dispatch({ type: 'customerManage/getLinkmanList', payload: { cstId: record.id, page: this.props.customerManage.linkmanPage } });//查询联系人列表
                        this.props.dispatch({ type: 'customerManage/getAgencyagreementList', payload: { id: record.id, page: this.props.customerManage.agencyagreementPage } });
                        this.props.dispatch({ type: 'customerManage/getRecAccList', payload: { cstId: record.id, page: this.props.customerManage.recAccPage } });
                        this.props.dispatch({ type: 'customerManage/getBuyerList', payload: { cstId: record.id, page: this.props.customerManage.buyerList } });
                        this.props.dispatch({ type: 'customerManage/getProductList', payload: { cstId: record.id, page: this.props.customerManage.productPage } });
                        this.props.dispatch({ type: 'drawer/getDrawerListByCstId', payload: { cstId: record.id, page: this.props.drawer.drawerPage, status: 1 } });
                        this.props.dispatch({ type: 'orderManage/queryOrderManageList', payload: { cstId: record.id, page: this.props.orderManage.page, status: 1 } });
                        this.props.dispatch({ type: 'businessAgreement/getAgreementlList', payload: { cstId: record.id, status: 1 } });
                        this.props.dispatch({ type: 'statement/getStatementsList', payload: { cstId: record.id, status: 2 } });
                        this.props.dispatch({ type: 'customerReport/getReconciliationList', payload: { cstId: record.id } });
                        this.props.dispatch({ type: 'customerReport/getOrderBilldetailList', payload: { cstId: record.id } });
                        this.props.dispatch({ type: 'customerManage/getListByCstIdForPage', payload: { cstId: record.id, page: this.props.customerManage.marketInfoPage } });
                        // this.props.dispatch({type: 'customerManage/getManagerList', payload: {}});

                        this.refs.customerDetail.handleOpen(customerDisabled, searchConditions, tabActiveKey, record.id, editCustomerDisable, "customerDetail");
                    }
                }
            });



        }

        handleSearch = () => {
            let values = this.props.form.getFieldsValue();
            let newPage = this.props.customerManage.page;
            newPage.page = 1;
            let time = values.time;
            this.props.dispatch({
                type: 'customerManage/queryCustomerManageList',
                payload: {
                    customerNO: values.customerNO,
                    cstName: values.cstName,
                    cstType: values.cstType,
                    cstManage: values.cstManage,
                    cstWaiter: values.cstWaiter,
                    beginTime: R.isNil(time) || R.isEmpty(time) ? null : time[0].format(dateFormat),
                    endTime: R.isNil(time) || R.isEmpty(time) ? null : time[1].format(dateFormat),
                    status: 4,
                    businessType: Constants.NUMBER_ONE,
                    page: newPage
                }
            });
        };



        columns = [
            { title: '客户编码', dataIndex: 'customerno', key: 'customerno' },

            // {title: '代理协议号', dataIndex: 'companyna', key: 'companyna', render(record) {
            //     return ("xx");
            // }},

            { title: '客户名称', dataIndex: 'companyname', key: 'companyname', },

            {
                title: '客户类型', render(record) {
                    if (R.isNil(record.companytypeName) || R.isEmpty(record.companytypeName)) {
                        return "未知";
                    } else {
                        return record.companytypeName;
                    }
                }
            },

            {
                title: '业务经理', render(record) {
                    if (R.isNil(record.managerName) || R.isEmpty(record.managerName)) {
                        return "未分配";
                    } else {
                        return record.managerName;
                    }
                }
            },

            {
                title: '跟单经理', render(record) {
                    if (R.isNil(record.waiterName) || R.isEmpty(record.waiterName)) {
                        return "未分配";
                    } else {
                        return record.waiterName;
                    }
                }
            },

            { title: '创建时间', dataIndex: 'createtime', key: 'createtime' },

            {
                title: '操作', key: 'key_oprator',

                render: (text, record, index) => {

                    let addOrderButton = <RightBox resource={RightContacts.ORDER.ORDER_MANAGE_ADD} split={false}><a href="#" onClick={this.onAddOrder.bind(this, record)}>添加订单</a><span className="ant-divider" /></RightBox>;
                    let addStatementButton = <RightBox resource={RightContacts.CUSTOMER.CUSTOMER_DETAIL_STATEMENT_ADD} split={false}> <a href="#" onClick={this.onAddStatement.bind(this, record)}>添加结算单</a></RightBox>;

                    return (
                        <span>
                            <RightBox resource={RightContacts.CUSTOMER.CUSTOMER_DETAIL_CUSTOMER_EDIT}><a href="#" onClick={this.onView.bind(this, record)}>信息维护</a>
                                <span className="ant-divider" /> </RightBox>
                            {addOrderButton}
                            {R.equals(record.csttype, "2") ? "" : addStatementButton}
                        </span>
                    );
                }
            }
        ];

        render() {
            let dataSouce = R.isNil(this.props.customerManage.dataSource) ? {} : this.props.customerManage.dataSource;
            let formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 18 } };
            const { getFieldDecorator } = this.props.form;
            let values = this.props.form.getFieldsValue();
            let time = values.time;
            let pagination = {
                showTotal: total => `共 ${total} 条数据`,
                pageSize: this.props.customerManage.page.size,
                total: this.props.customerManage.page.totalRow,
                showSizeChanger: true,
                current: this.props.customerManage.page.page,
                onShowSizeChange: (current, size) => {
                    let newPage = this.props.customerManage.page;
                    newPage.size = size;
                    newPage.page = 1;
                    this.props.dispatch({
                        type: 'customerManage/queryCustomerManageList',
                        payload: {
                            customerNO: values.customerNO,
                            cstName: values.cstName,
                            cstType: values.cstType,
                            cstManage: values.cstManage,
                            cstWaiter: values.cstWaiter,
                            beginTime: R.isNil(time) || R.isEmpty(time) ? null : time[0].format(dateFormat),
                            endTime: R.isNil(time) || R.isEmpty(time) ? null : time[1].format(dateFormat),
                            status: 4,
                            businessType: Constants.NUMBER_ONE,
                            page: newPage
                        }
                    });
                },
                onChange: (pageNumber, pageSize) => {
                    let newPage = this.props.customerManage.page;
                    newPage.page = pageNumber;
                    this.props.dispatch({
                        type: 'customerManage/queryCustomerManageList',
                        payload: {
                            customerNO: values.customerNO,
                            cstName: values.cstName,
                            cstType: values.cstType,
                            cstManage: values.cstManage,
                            cstWaiter: values.cstWaiter,
                            beginTime: R.isNil(time) || R.isEmpty(time) ? null : time[0].format(dateFormat),
                            endTime: R.isNil(time) || R.isEmpty(time) ? null : time[1].format(dateFormat),
                            status: 4,
                            businessType: Constants.NUMBER_ONE,
                            page: newPage
                        }
                    });
                }
            }
            return (
                <div>

                    <Row>
                        <Col span={7}><FormItem {...formItemLayout} label={'客户代码'}>{getFieldDecorator('customerNO')(<Input />)}</FormItem></Col>
                        <Col span={7}><FormItem {...formItemLayout} label={'客户名称'}>{getFieldDecorator('cstName')(<Input />)}</FormItem></Col>
                    </Row>
                    <Row>
                        <Col span={7}><FormItem {...formItemLayout} label={'业务经理'}>{getFieldDecorator('cstManage')(<Input />)}</FormItem></Col>
                        <Col span={7}><FormItem {...formItemLayout} label={'跟单经理'}>{getFieldDecorator('cstWaiter')(<Input />)}</FormItem></Col>
                    </Row>
                    <Row>
                        <Col span={7}><FormItem {...formItemLayout} label={'客户类型'}>
                            {getFieldDecorator('cstType')(
                                <BizParams sprCode={"cstType"} style={{ width: '100%' }} all={true} />
                            )}
                        </FormItem></Col>
                        <Col span={7}>
                            <FormItem {...formItemLayout} label={'创建时间'}>
                                {getFieldDecorator('time', {})(
                                    <RangePicker
                                        style={{ width: 265 }}
                                        showTime={{ format: 'YYYY-MM-DD' }}
                                        format="YYYY-MM-DD"
                                        placeholder={['开始时间', '结束时间']}
                                    />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={7} style={{ float: 'right' }}>
                            <Button type="primary" icon="search" style={{ marginRight: 5 }} onClick={this.handleSearch.bind(this)}>查询</Button>
                        </Col>

                    </Row>

                    <Table dataSource={this.props.customerManage.list} columns={this.columns} bordered={true} size={'middle'} pagination={pagination} />

                    <CustomerDetail ref={"customerDetail"} cstId={dataSouce.id} drawers={this.props.drawer} {...this.props.customerManage}
                        orderManage={this.props.orderManage}
                        businessAgreement={this.props.businessAgreement}
                        statement={this.props.statement}
                        dispatch={this.props.dispatch} showPA={true}
                        capital={this.props.capital}
                        customerReport={this.props.customerReport}
                        blacklist={this.props.blacklist}
                        handleSearch={this.handleSearch} />

                    <Statement wrappedComponentRef={(inst) => this.statement = inst} cstId={dataSouce.id} customerManage={this.props.customerManage}
                        dispatch={this.props.dispatch} />

                    <OrderDetail ref={"orderDetail"} cstId={dataSouce.id} {...this.props.orderManage} dispatch={this.props.dispatch} />

                </div>
            )
        }
    })


)
